import os

from django.conf import settings
from rest_framework.response import Response
from rest_framework.views import APIView
from shortuuid import uuid

from apps.image.serializers import UploadImageSerializers


class UploadImageView(APIView):
    def post(self, request):
        serializer = UploadImageSerializers(data=request.data)
        print("1")
        if serializer.is_valid():
            file = serializer.validated_data['image']
            filename = uuid() + os.path.splitext(file.name)[-1]
            path = settings.MEDIA_ROOT / filename
            try:
                with open(path, 'wb') as fp:
                    for chunk in file.chunks():
                        fp.write(chunk)
            except Exception:
                return Response({'errno': 1,
                                 'message': '图片上传失败'})
            file_url = settings.MEDIA_URL + filename
            return Response({'errno': 0,
                             'data': {
                                 'url': file_url,
                                 'alt': '',
                                 'herf': file_url
                             }})
        else:
            print(list(serializer.errors.values())[0][0])
            return Response({'errno': 1,
                             'message': list(serializer.errors.values())[0][0]})
